package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import com.itheima.util.SMSUtils;
import com.itheima.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送手机短信验证码
     * */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) throws Exception {
        //获取手机号
        String phone = user.getPhone();
        //手机号码不为空，发送验证码
        if (StringUtils.isNotEmpty(phone)) {
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
            //调用阿里云提供的短信服务API完成短信发送
            SMSUtils.sendShortMessage(phone,code);

            //需要将生成的验证码保存到Session中
//            session.setAttribute("code",code);
//            session.setAttribute("phone",phone);

            //将生成的验证码存入Redis里面，并限制时间5分钟。
            redisTemplate.opsForValue().set("code",code,5, TimeUnit.MINUTES);
            redisTemplate.opsForValue().set("phone",phone,5, TimeUnit.MINUTES);

            return R.success("手机验证码发送成功");
        }
        return R.error("手机验证码发送失败");
    }

    /**
    * 移动端用户登录(User里面没有code，可以使用UserDto接收，或者map集合)
    * */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        log.info("map{}",map.toString());
        //获取手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        //从Session中获取验证码，并进行比对
//        String codeInSession = session.getAttribute("code").toString();
//        String phoneInSession = session.getAttribute("phone").toString();

        //从Redis中获取缓存验证码
        String codeInSession =(String) redisTemplate.opsForValue().get("code");
        String phoneInSession =(String) redisTemplate.opsForValue().get("phone");

        if (code != null && code.equals(codeInSession) && phone.equals(phoneInSession)) {
            //比对成功，可以成功登录
            //创建条件构造器
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phone);
            User user = userService.getOne(lqw);

            //如果数据库中不存在该用户，则进行自动注册
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //将用户id存入session中
            session.setAttribute("user",user.getId());

            //如果用户登录成功，删除redis中缓存的验证码
            redisTemplate.delete("code");
            redisTemplate.delete("phone");

            return R.success(user);
        }

        return R.error("手机验证码输入错误");
    }

    @PostMapping("/loginout")
    public R<String> loginOut(HttpSession session) {
        log.info("当前用户id{}",BaseContext.getCurrentId());
        session.removeAttribute("user");
        return R.success("退出登录成功");

    }

}
